package com.xlh.service.courseTest.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.xlh.dao.courseTest.ExperimentStatisticsPassMapper;
import com.xlh.dao.courseTest.ext.ExperimentStatisticsPassMapperExt;
import com.xlh.dto.courseTest.experiment.ExperimentChapterStatisticsPassDTO;
import com.xlh.dto.courseTest.experiment.ExperimentStatisticsTaskPassDTO;
import com.xlh.dto.user.UserInfoDTO;
import com.xlh.pojo.courseTest.ExperimentStatisticsPass;
import com.xlh.pojo.courseTest.ExperimentStatisticsTaskPass;
import com.xlh.pojo.courseTest.example.ExperimentStatisticsPassExample;
import com.xlh.service.courseTest.ExperimentStatisticsTaskPassService;
import com.xlh.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author sy
 */
@Service
@Slf4j
public class ExperimentStatisticsTaskPassServiceImpl implements ExperimentStatisticsTaskPassService {

    @Autowired
    private ExperimentStatisticsPassMapper experimentStatisticsPassMapper;

    @Autowired
    private ExperimentStatisticsPassMapperExt experimentStatisticsPassMapperExt;

    /**
     * 查询学生实验情况根据userID和taskID
     * @param courseId
     * @param classId
     * @param taskIds
     * @param userIds
     * @return
     */
    @Override
    public List<ExperimentStatisticsTaskPassDTO> findExperimentByUserId(Long courseId,
                                                                        Long classId,
                                                                        List<Long> taskIds,
                                                                        List<Long> userIds) {

        List<Integer> integerTaskIds = taskIds.stream().map(Long::intValue).collect(Collectors.toList());
        List<Integer> integerUserIds = userIds.stream().map(Long::intValue).collect(Collectors.toList());
        ExperimentStatisticsPassExample experimentStatisticsPassExample = new ExperimentStatisticsPassExample();
        experimentStatisticsPassExample.createCriteria().andCourseIdEqualTo(courseId.intValue())
                                                        .andClassIdEqualTo(classId.intValue()).andChapterIdIn(integerTaskIds)
                                                        .andUserIdIn(integerUserIds);
        List<ExperimentStatisticsPass> userTaskStatus = experimentStatisticsPassMapper.selectByExample(experimentStatisticsPassExample);
        // 执行数据组装
        List<ExperimentStatisticsTaskPass> userTaskRecord = createUserTaskRecords( courseId, classId, taskIds, userIds );
        // 执行数据替换
        List<ExperimentStatisticsTaskPassDTO> result = replaceUserTaskRecord(userTaskRecord, userTaskStatus);

        return result;
    }

    /**
     * 学员章节的通过情况
     * @param experimentChapterId 章节ID|任务ID
     * @param userInfoDTOs 当前章节下所有学生人数
     * @return
     */
    @Override
    public ExperimentChapterStatisticsPassDTO loadExperimentPass(Long experimentChapterId, List<UserInfoDTO> userInfoDTOs) {

        ExperimentChapterStatisticsPassDTO passDTO = new ExperimentChapterStatisticsPassDTO();
        if(CollectionUtil.isEmpty(userInfoDTOs)){
            passDTO.setPassUsers(Lists.newArrayList("0"));
            passDTO.setNoPassUsers(Lists.newArrayList("0"));
            passDTO.setPassingRate(0d);
            return passDTO;
        }
        List<Integer> userInfos = userInfoDTOs.stream().map(userInfoDTO -> userInfoDTO.getId().intValue()).collect(Collectors.toList());
        List<UserInfoDTO> passUser = experimentStatisticsPassMapperExt.selectPassUser(experimentChapterId, userInfos);
        // 获取未通过章节信息的学生
        List<UserInfoDTO> noPassUser = getNoPassUsers(userInfoDTOs,passUser);
        List<String> passUserStr = passUser.stream().map(user -> user.getName()).collect(Collectors.toList());
        List<String> noPassUserStr = noPassUser.stream().map(user -> user.getName()).collect(Collectors.toList());

        passDTO.setPassUsers(passUserStr);
        passDTO.setNoPassUsers(noPassUserStr);
        passDTO.completePassingRate();

        return passDTO;
    }

    /**
     * 获取未通过学生名单
     * @param allUsers 所有的用户
     * @param passUsers 已通过的用户
     * @return
     */
    private List<UserInfoDTO> getNoPassUsers(List<UserInfoDTO> allUsers, List<UserInfoDTO> passUsers) {

        CopyOnWriteArrayList<UserInfoDTO> userInfoDTOS = Lists.newCopyOnWriteArrayList(allUsers);
        for (UserInfoDTO userInfoDTO : userInfoDTOS) {
            for (UserInfoDTO passUser : passUsers) {
                if(userInfoDTO.getId().equals(passUser.getId())){
                    userInfoDTOS.remove(userInfoDTO);
                }
            }
        }

        return userInfoDTOS;
    }

    /**
     * 替换用户数据
     * @param userTaskRecords 替换对象
     * @param userTaskStatus 被替换对象
     * @return
     */
    private List<ExperimentStatisticsTaskPassDTO> replaceUserTaskRecord(List<ExperimentStatisticsTaskPass> userTaskRecords, List<ExperimentStatisticsPass> userTaskStatus) {

        List<ExperimentStatisticsTaskPass> result = Lists.newArrayList();

        outer:
        for (ExperimentStatisticsTaskPass userTaskStatu : userTaskRecords) {
            for (ExperimentStatisticsPass userTaskRecord : userTaskStatus) {
                if(userTaskStatu.getUserId().equals(userTaskRecord.getUserId()) &&
                        userTaskStatu.getTaskId().equals(userTaskRecord.getChapterId())){
                    ExperimentStatisticsTaskPass transform = BeanUtil.transform(ExperimentStatisticsTaskPass.class, userTaskRecord);
                    transform.setTaskId(userTaskRecord.getChapterId());
                    result.add(transform);
                    continue outer;
                }
            }
            result.add(userTaskStatu);
        }

        List<ExperimentStatisticsTaskPassDTO> resultDto = convertTaskPassToPassDTO(result);

        return resultDto;
    }


    /**
     * 将pojo对象转换为DTO对象
     * @param result
     * @return
     */
    private List<ExperimentStatisticsTaskPassDTO> convertTaskPassToPassDTO(List<ExperimentStatisticsTaskPass> result) {

        List<ExperimentStatisticsTaskPassDTO> resultDao = Lists.newArrayList();
        for (ExperimentStatisticsTaskPass experimentStatisticsTaskPass : result) {
            ExperimentStatisticsTaskPassDTO convertResult = BeanUtil.transform(ExperimentStatisticsTaskPassDTO.class, experimentStatisticsTaskPass);
            if(experimentStatisticsTaskPass.getPass() != null){
                if(ExperimentStatisticsTaskPass.PASS.equals(String.valueOf(experimentStatisticsTaskPass.getPass()))){
                    convertResult.setPass(true);
                }else{
                    convertResult.setPass(false);
                }
            }
            resultDao.add(convertResult);
        }
        return resultDao;
    }

    /**
     * 生成逐条的用户任务对象
     * @param courseId
     * @param classId
     * @param taskIds
     * @param userIds
     * @return
     */
    private List<ExperimentStatisticsTaskPass> createUserTaskRecords(Long courseId, Long classId, List<Long> taskIds, List<Long> userIds) {

        List<ExperimentStatisticsTaskPass> result = Lists.newArrayList();
        for (Long taskId : taskIds) {
            for (Long userId : userIds) {
                ExperimentStatisticsTaskPass experimentStatisticsTaskPass = new ExperimentStatisticsTaskPass();
                experimentStatisticsTaskPass.setCourseId(courseId);
                experimentStatisticsTaskPass.setClassId(classId);
                experimentStatisticsTaskPass.setTaskId(taskId);
                experimentStatisticsTaskPass.setUserId(userId);
                result.add(experimentStatisticsTaskPass);
            }
        }
        return result;
    }

}